package nix.mall.search.listener;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import nix.mall.common.pojo.SearchItem;
import nix.mall.search.mapper.SearchItemMapper;

/**
 * 商品添加事件监听器，同步索引库
 */
public class ItemAddListener implements MessageListener  {

	@Autowired
	private SearchItemMapper searchItemMapper;
	
	@Autowired
	private SolrServer solrServer;
	
	@Override
	public void onMessage(Message message) {
		try {
			if (message instanceof TextMessage) {
				// 从消息中取商品Id
				TextMessage textMessage = (TextMessage) message;
				String text = textMessage.getText();
				long itemId = Long.parseLong(text);
				// 根据商品Id查询商品信息
				// 等待商品添加事务提交完成
				Thread.sleep(1000);
				SearchItem searchItem = searchItemMapper.getItemById(itemId);
				// 创建文档对象
				SolrInputDocument document = new SolrInputDocument();
				// 向文档对象添加域
				document.addField("id", searchItem.getId());
				document.addField("item_title", searchItem.getTitle());
				document.addField("item_sell_point", searchItem.getSell_Point());
				document.addField("item_price", searchItem.getPrice());
				document.addField("item_image", searchItem.getImage());
				document.addField("item_category_name", searchItem.getCategory_name());
				document.addField("item_desc", searchItem.getItemDesc());
				// 把文档写入索引库
				solrServer.add(document);
				// 提交
				solrServer.commit();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
